Ext.define('UX.codeview.FieldX', {
	extend : 'Ext.form.field.Trigger',
	alias : 'widget.codeviewfieldx',
	requires : [ 'UX.codeview.SingleCodeviwePopup', 'UX.codeview.MultiCodeviewPopup' ],
	componentCls : 'ux-codeviewfieldx',
	// fieldStyle : 'border-width : 1px !important;',
	// triggerBaseCls : 'ux-codeviewx-border',
	// trigger1Cls : 'ux-codeviewx-trigger',
	triggerBaseCls : 'x-form-trigger',
	triggerCls : 'x-form-search-trigger',
	triggerWidth : 20,

	readOnlyCls : Ext.baseCSSPrefix + 'trigger-readonly',

	disabledEnter : false,
	// default > component, cell editor > editor
	fieldType : 'component',

	fieldId : '',
	fieldDataIndex : '',

	dspFields : [],

	pStore : null,
	remoteFilter : true,
	params : {},
	factoryConditionEnabled : true,
	serviceUrl : '',
	servicePath : '',
	table : '',
	// ex) {column : "columnName", ascending : true or false}
	order : [],
	// ex) {column : "columnName" , value : value or function, scope: this,
	// operator : "like"}
	condition : [],
	pageSize : window.CODEVIEW_PAGESIZE || 1000,
	showFailureMsg : true,

	pColumns : [ {
		text : 'Name',
		dataIndex : 'key1',
		disabledSearch : false,
		disabledEnter : false,
		// component > field ItemId, Name
		// editor > column dataIndex
		// fieldId : '',
		flex : 1
	}, {
		text : 'Description',
		dataIndex : 'data1',
		disabledSearch : false,
		disabledEnter : false,
		flex : 2
	} ],
	defaultPopupConfig : {},
	fieldSearch : false,

	multiSelect : false,
	multiSelectCount : 100,
	delimiter : ',',
	selectedValues : [],

	tableId : '',
	pRecord : null,
	store : null,

	constructor : function(configs) {
		// type
		var config = Ext.clone(configs || {});
		var cdvType = config.type || config.cdvType;
		if (cdvType) {
			config.cdvType = cdvType.toLowerCase();
			delete config.type;
		} else {
			config.cdvType = 'cd';
		}

		// service
		if (Ext.isObject(config.service)) {
			config.serviceUrl = config.service.name;
			config.servicePath = config.service.path || '';
			config.cdvType = 'service';
			delete config.service;
		}

		// pop-up Columns
		if (config.columns) {
			this.isGcmTableColumn = true;
			config.pColumns = config.columns;
			Ext.Array.each(config.pColumns, function(col) {
				if (Ext.isEmpty(col.width) && Ext.isEmpty(col.flex)) {
					col.flex = 1;
				}
			});
			delete config.columns;
		}

		// pop-up title
		if (!config.title && config.fieldLabel) {
			config.title = config.fieldLabel;
		}

		if (config.table) {
			delete config.tableId;
		}

		this.callParent([ config ]);
	},

	initComponent : function() {
		this.callParent();

		this.addEvents('beforestoreload', 'afterstoreload', 'select', 'showpopup', 'closepopup', 'clearfieldvalue', 'setfieldvalue');

		this.pStore = this.createStore();
		if (this.pStore) {
			this.pStore.mon(this.pStore, {
				load : function(store, records, success) {
					this.fireEvent('afterstoreload', this, store, records, success);
					if (this.codeviewPopup) {
						this.codeviewPopup.fireEvent('afterstoreload', this, store, records, success);
					}
				},
				scope : this
			});
		}

		var event = {
			setfieldvalue : function(me, records) {
				this.setFieldValue(records);
			},
			clearfieldvalue : function(me) {
				this.clearFieldValue();
			},
			scope : this
		};

		if (this.disabledEnter === false) {
			event.specialkey = function(me, e) {
				if (e.getKey() == e.ENTER) {
					me.onTrigger1Click(e);
				}
			};
		}
		this.mon(this, event);
	},

	initEvents : function() {
		var me = this;
		me.callParent();
		if (!me.editable) {
			me.mon(me.inputEl, 'click', me.onTrigger1Click, me);
		}
		if (Ext.isGecko) {
			me.inputEl.dom.setAttribute('autocomplete', 'off');
		}
	},

	setFieldValue : function(records) {
		var value = '';
		var fieldId = this.fieldId || '';
		var fieldDataIndex = this.fieldDataIndex;

		if (this.fieldType === 'editor') {
			this.up().cancelEdit();
		}

		if (this.multiSelect === true) {
			var selectedData = [];
			Ext.Array.each(records, function(record) {
				selectedData.push(record.data);
			});

			this.setSelectedValues(selectedData, this.fieldDataIndex);
		} else {
			value = records.get(fieldDataIndex);

			if (this.fieldType === 'editor') {
				var pRecord = this.pRecord;

				pRecord.set(fieldId, value);

				Ext.Array.each(this.dspFields, function(config) {
					var value = records.get(config.dspDataIndex)
					pRecord.set(config.dspFieldId, value);
				}, this);
			} else {
				this.setValue(value);
			}
		}

		this.fireEvent('select', this, records);
	},

	getFieldValue : function() {
		if (this.fieldType === 'editor') {
			return this.pRecord.get(this.fieldId);
		} else {
			return this.getValue();
		}
	},

	clearFieldValue : function() {
		if (this.fieldType == 'editor') {
			this.pRecord.set(this.fieldId, '');
			Ext.Array.each(this.dspFields, function(config) {
				this.pRecord.set(config.dspFieldId, '');
			}, this);
		} else {
			this.setValue('');
		}

		if (this.multiSelect === true) {
			this.setSelectedValues([]);
		}
	},

	setSelectedValues : function(values, displayfield) {
		this.selectedValues = values;

		if (Ext.isArray(values) && !Ext.isEmpty(displayfield)) {
			var data = [];
			Ext.Array.each(values, function(v) {
				data.push(v[displayfield]);
			}, this);

			var value = data.join(this.delimiter);
			if (value == this.delimiter) {
				value = '';
			}

			if (this.fieldType === 'editor') {
				this.pRecord.set(fieldId, value);
			} else {
				this.setValue(value);
			}
		}
	},

	getSelectedValues : function() {
		return Ext.clone(this.selectedValues) || [];
	},

	onTrigger1Click : function(e) {
		var pCmp = this.up();
		var pXtype = pCmp ? pCmp.xtype : '';
		if (pXtype == 'editor') {
			this.fieldType = 'editor';
		} else {
			this.fieldType = 'component';
		}

		if (e.type === 'keydown' && this.fieldType == 'editor') {
			return false;
		}

		if (this.fieldType === 'editor') {
			var record = pCmp.editingPlugin.context.record;
			if (record) {
				this.pRecord = record;
				if (this.tableId) {
					var table = record.get(this.tableId);
					this.table = table;

					Ext.apply(this.pStore.proxy.extraParams, {
						table : table
					});
				}
			}
		}

		var params = Ext.clone(this.params);
		var selected = {};
		if (this.fireEvent('beforestoreload', this, this.pStore, params, selected) === false) {
			return false;
		}

		if (this.cdvType === 'cd' && this.table && !this.isGcmTableColumn) {
			YX.ZbusRpc.request({
				url : 'BasViewTableService',
				params : {
					procstep : '1',
					tableName : this.table
				},
				success : function(result) {
					var gcmColumns = [];

					for (var i = 1; i <= 5; i++) {
						var dataIndex = 'key' + i;
						if (text) {
							gcmColumns.push({
								text : dataIndex,
								dataIndex : dataIndex,
								disabledSearch : false,
								disabledEnter : false,
								flex : 1
							});
						}
					}
					for (i = 1; i <= 5; i++) {
						var dataIndex = 'data' + i;
						if (text) {
							gcmColumns.push({
								text : dataIndex,
								dataIndex : dataIndex,
								disabledSearch : false,
								disabledEnter : false,
								flex : 1
							});
						}
					}
					this.isGcmTableColumn = true;
					this.pColumns = gcmColumns;
					this.showPopup(params, selected.values || []);
				},
				scope : this
			});
		} else {
			this.showPopup(params, selected.values || []);
		}
	},

	showPopup : function(params, selectedValues) {
		var config = Ext.clone(this.defaultPopupConfig);
		var columns = Ext.clone(this.pColumns);
		var fcIndexs = [];
		this.dspFields = [];

		Ext.Array.each(columns, function(col, index) {
			if (!Ext.isEmpty(col.fieldId)) {
				if (this.fieldType === 'editor') {
					if (col.fieldId == this.name) {
						fcIndexs.push(index);
					}
				} else {
					if (col.fieldId == this.itemId || col.fieldId == this.name) {
						fcIndexs.push(index);
					}
				}
			}
		}, this);

		var fcIndex = fcIndexs[fcIndexs.length - 1];
		if (Ext.isEmpty(fcIndex)) {
			fcIndex = 0;
			if (this.fieldType === 'editor') {
				columns[0].fieldId = this.name;
			} else {
				columns[0].fieldId = this.itemId || this.name;
			}
		}

		Ext.Array.each(columns, function(col, index) {
			if (index === fcIndex) {
				this.fieldId = col.fieldId;
				this.fieldDataIndex = col.dataIndex;

				if (this.multiSelect === false && this.fieldSearch === true) {
					var value = '';
					if (this.fieldType === 'editor') {
						value = this.pRecord.get(col.fieldId);
					} else {
						value = this.getValue();
					}
					col.searchValue = value;
				}
			} else {
				delete col.fieldId;

				if (!Ext.isEmpty(col.dspFieldId)) {
					this.dspFields.push({
						dspFieldId : col.dspFieldId,
						dspDataIndex : col.dataIndex
					})
				}
			}
		}, this);

		Ext.apply(config, {
			title : this.title,
			codeviewField : this,
			pStore : this.pStore,
			pColumns : columns,
			pParams : params,
			pCdvType : this.cdvType,
			pCondition : Ext.clone(this.condition),
			pPageSize : this.pageSize,
			pShowFailureMsg : this.showFailureMsg
		});

		if (this.multiSelect === false) {
			this.codeviewPopup = Ext.create('UX.codeview.SingleCodeviwePopup', config).show();
		} else {
			if (selectedValues.length === 0 && !Ext.isEmpty(this.getFieldValue())) {
				var valeus = this.getFieldValue().split(this.delimiter);
				Ext.Array.each(valeus, function(value) {
					var v = {};
					v[this.fieldDataIndex] = value;
					selectedValues.push(v);
				}, this);
			}

			config.pMultiSelectCount = this.multiSelectCount;
			config.pDelimiter = this.delimiter;
			config.pSelectedValues = selectedValues;
			this.codeviewPopup = Ext.create('UX.codeview.MultiCodeviewPopup', config).show();
		}
	},

	bindStore : function(store) {
		var oldStore = this.pStore;

		if (oldStore != store) {
			oldStore.destroyStore();

			this.pStore = store;

			this.pStore.mon(this.pStore, {
				load : function(store, records, success) {
					this.fireEvent('afterstoreload', this, store, records, success);
				},
				scope : this
			});
		}
	},

	// store
	createStore : function() {
		var params = {};
		var serviceUrl = '';
		var servicePath = '';
		var fields = this.createFields();
		if (this.cdvType == 'memory') {
			return Ext.create('Ext.data.Store', {
				fields : fields
			});
		} else if (this.serviceUrl || this.cdvType == 'service') {
			this.cdvType = 'service';
			serviceUrl = this.serviceUrl;
			servicePath = this.servicePath;
		} else if (this.cdvType == 'cd' || this.cdvType == 'table') {
			params = {
				procstep : '1',
				select : fields,
				table : this.table,
				type : this.cdvType
			};
			serviceUrl = 'BasViewCommonDataSetupDetailService';
			servicePath = 'cdsDtlList';
		}

		return Ext.create('Ext.data.JsonStore', {
			autoLoad : false,
			fields : fields,
			remoteFilter : this.remoteFilter,
			pageSize : this.pageSize,
			proxy : {
				type : 'zbusrpc',
				module : serviceUrl,
				params : params,
				reader : {
					type : 'json',
					root : servicePath,
					totalProperty : 'total'
				}
			}
		});
	},

	createFields : function() {
		var fields = [];
		var columns = this.pColumns || [];
		var conditions = this.condition || [];

		Ext.Array.each(columns, function(col) {
			if (col.dataIndex) {
				fields.push(col.dataIndex);
			}
		});

		Ext.Array.each(conditions, function(cond) {
			if (cond.column) {
				if (Ext.Array.contains(fields, cond.column) === false) {
					fields.push(cond.column);
				}
			}
		});

		return fields;
	}
});